<?php
//massive_long_tail_words 海量长尾词挖掘 取前5000条
header('Content-Type:text/html;charset=utf8');
include_once "../db_orm.php";
include_once "../function.php";

use Illuminate\Database\Capsule\Manager as DB;

$db_table1 = 'product';
$db_table2 = 'massive_long_tail_words';
$date = $_GET['date'];

$res = DB::table($db_table1)
    ->leftJoin($db_table2, function ($join) use ($db_table1, $db_table2) {
        $join->on($db_table1 . '.name', '=', $db_table2 . '.keyword')
            ->where($db_table2 . '.p_id', '=', 0);
    })
    ->select($db_table1 . '.id', $db_table1 . '.name', $db_table2 . '.p_id')
    ->where($db_table2 . '.p_id', '=', null)
    ->orderBy($db_table1 . '.id')
    ->limit('5000')
    ->get();
//var_dump($res);exit;
$host = "http://apis.5118.com";
$path = "/keyword/word";
$method = "POST";
$apikey = "C038451CF96D4DBAA06635E87DDBF260";
$headers = array();
array_push($headers, "Authorization:" . $apikey);
//根据API的要求，定义相对应的Content-Type
array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
$url = $host . $path;

if (!empty($res)) {
    foreach ($res as $key => $value) {
        $insert_id = DB::table($db_table2)->insertGetId(['keyword' => $value['name'], 'p_id' => 0]);

        for ($page_index = 1; $page_index < 6; $page_index++) {
            $bodys = "keyword=" . $value['name'] . "&page_index=" . $page_index;

            $bodyInfo = curl_post($url, $headers, $bodys);
            $bodyInfo = json_decode($bodyInfo, true);
            if ($bodyInfo['errcode'] == 0) {
//                var_dump($bodyInfo['data']);exit;

                //当前页无数据跳出for循环
                if (!empty($bodyInfo['data']['word'])) {
                    $word = $bodyInfo['data']['word'];

                    foreach ($word as &$v) {
                        $v['p_id'] = $insert_id;
                    }
                    DB::table($db_table2)->insert($word);
                } else {
                    break;
                }
            } else {
                echo $bodyInfo['errmsg'] . "\n";
//                exit;
            }
        }
        echo ($key + 1) . "/" . count($res) . "\n";
        usleep(500000);
    }
}
echo 'succ';